package com.guit.hrms.controller;

import com.guit.hrms.dto.LocationCheckInDTO;
import com.guit.hrms.dto.SetCheckInTimeDTO;
import com.guit.hrms.dto.TransactionDTO;
import com.guit.hrms.po.*;
import com.guit.hrms.po.utilsPO.PageBean;
import com.guit.hrms.po.utilsPO.Result;
import com.guit.hrms.service.AttendanceService;
import com.guit.hrms.utils.ThreadLocalUtil;
import com.guit.hrms.vo.EmpSignVO;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/api/attendance")
public class AttendanceController {
    @Autowired
    private AttendanceService attendanceService;

    /**
     * 设置打卡时间
     * @param setCheckInTimeDTO  设置打卡时间的信息
     * @return 结果
     */
    @PostMapping("/setCheckInTime")
    public Result setCheckInTime(@RequestBody @Valid SetCheckInTimeDTO setCheckInTimeDTO){
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer result = attendanceService.setCheckInTime(setCheckInTimeDTO);
        if (result == 1){
            return Result.success("设置成功");
        } else {
            return Result.error("设置失败");
        }
    }

    /**
     * 判断是否在打卡日的打卡时间内
     * @param deptId 部门id
     * @return 结果
     */
    @GetMapping("/getCheckInTime")
    public Result getCheckInTime(Integer deptId, Integer deptType){
        SetCheckInTimeDTO checkInTime = attendanceService.getCheckInTime(deptId, deptType);
        if (checkInTime != null){
            return Result.success(checkInTime);
        } else {
            return Result.error("未设置打卡时间");
        }
    }

    /**
     * 获取各部门的打卡设置信息
     * @param page 页码
     * @param pageSize 每页大小
     * @param deptType 部门类型
     * @param deptId 部门id
     * @return 结果
     */
    @GetMapping("/getAllCheckInTime")
    public Result getAllCheckInTime(@RequestParam(defaultValue = "1") Integer page ,
                                    @RequestParam(defaultValue = "10") Integer pageSize,
                                    Integer deptType, Integer deptId){
        PageBean checkInTimeList = attendanceService.getAllCheckInTime(page, pageSize, deptId, deptType);
        return Result.success(checkInTimeList);
    }

    /**
     * 定位打卡
     * @param locationCheckInDTO 定位打卡的信息
     * @return 结果
     */
    @PostMapping("/location")
    public Result locationCheckIn(@RequestBody LocationCheckInDTO locationCheckInDTO){
        System.out.println(locationCheckInDTO.toString());
        Map<String,Object> map = ThreadLocalUtil.get();
        String employeeId = (String) map.get("employeeId");
        Integer deptId = (Integer) map.get("department");
        Integer deptType = (Integer) map.get("deptType");
        locationCheckInDTO.setEmployeeId(employeeId);
        locationCheckInDTO.setDeptId(deptId);
        locationCheckInDTO.setDeptType(deptType);
        Integer result = attendanceService.locationCheckIn(locationCheckInDTO);
        if (result == 1){
            return Result.success("签到成功！");
        } else if (result == 2) {
            return Result.error("您所在的部门没有设置打卡要求！");
        } else {
            return Result.error("签到失败！");
        }
    }


    /**
     * 获取所有考勤记录
     * @return 所有员工的考勤记录
     */
    @GetMapping("/getRecords")
    public Result getRecords(@RequestParam(defaultValue = "1") Integer page ,
                             @RequestParam(defaultValue = "10") Integer pageSize,
                             LocalDate checkInDate, Integer isCheckIn,
                             Integer checkInStatus, Integer circumstance){
        PageBean empSignList = attendanceService.getRecords(page, pageSize, checkInDate, isCheckIn, checkInStatus, circumstance);
        System.out.println("empSignList = " + empSignList);
        return Result.success(empSignList);
    }

    /**
     * 获取单个员工考勤记录
     * @return 单个员工的考勤记录
     */
    @GetMapping("/getRecords/{employeeId}")
    public Result getRecordsById(@PathVariable String employeeId){
        List<EmpSign> empSignList = attendanceService.getRecordsById(employeeId);
        return Result.success(empSignList);
    }

    /**
     * 获取自己的考勤记录
     * @return 单个员工的考勤记录
     */
    @GetMapping("/getRecords/personal/all")
    public Result getPersonalRecordsByEmployeeId(){
        Map<String,Object> map = ThreadLocalUtil.get();
        String employeeId = (String) map.get("employeeId");
        List<EmpSign> empSignList = attendanceService.getRecordsById(employeeId);
        return Result.success(empSignList);
    }

    /**
     * 获取员工个人当天考勤记录
     * @return 员工个人当天考勤记录
     */
    @GetMapping("/getRecords/personal")
    public Result getPersonalRecords(){
        Map<String,Object> map = ThreadLocalUtil.get();
        String employeeId = (String) map.get("employeeId");
        EmpSignVO empSignVO = attendanceService.getPersonalRecords(employeeId);
        return Result.success(empSignVO == null ? new EmpSignVO() : empSignVO);
    }

    /**
     * 申请请假
     * @param transaction 事务申请
     * @return Result
     */
    @PostMapping("/leave")
    public Result transaction(@RequestBody Transaction transaction){

        Integer id = attendanceService.affairs(transaction);
        return Result.success(id);
    }

    /**
     * 个人查看请假记录
     * @return 个人事务表
     */
    @GetMapping("/leaveRecord")
    public Result getTransaction(@RequestParam(defaultValue = "1") Integer page ,
                                 @RequestParam(defaultValue = "10") Integer pageSize,
                                 Integer type, Integer approvalStatus,Integer revokeStatus, Integer extensionStatus){
        System.out.println(revokeStatus+"    "+extensionStatus);
        PageBean pageBean = attendanceService.getTransaction(page,pageSize,type,approvalStatus,revokeStatus,extensionStatus);
        return Result.success(pageBean);
    }

    /**
     * 删除自己的请假记录
     * @param ids 要删除记录的id
     * @return 结果
     */
    @DeleteMapping("/deleteLeaveRecord/{ids}")
    public Result deleteTransaction(@PathVariable List<Integer> ids){
        System.out.println(ids);
        attendanceService.deleteLeaveRecord(ids);
        return Result.success();
    }

    /**
     * 自己的销假
     * @param id 要销假记录的id
     * @return 结果
     */
    @PatchMapping("/cancelLeaveRecord/{id}")
    public Result cancelTransaction(@PathVariable Integer id){
        Integer result = attendanceService.cancelTransaction(id);
        if (result == 0){
            return Result.error();
        } else {
            return Result.success();
        }
    }

    /**
     * 更新事务
     * @param id 要更新的记录的id
     * @param transaction 更新的内容
     * @return 结果
     */
    @PatchMapping("/leaveRecord/{id}")
    public Result updateTransaction(@PathVariable Integer id, @RequestBody Transaction transaction){
        if (id == null && ((transaction.getType() == null || transaction.getType() == 0)|| transaction.getStartTime() == null || transaction.getEndTime() == null)){
            return Result.error("请选择要更新的记录和要更新的内容");
        } else if (transaction.getEndTime().isBefore(LocalDateTime.now()) && transaction.getStartTime().isAfter(transaction.getEndTime())){
            System.out.println("接收到请求");
            return Result.error("请确保时间设置正确");
        } else {
            transaction.setId(id);
            Integer result = attendanceService.updateTransaction(transaction);
            if (result == 0){
                return Result.error();
            } else {
                return Result.success();
            }
        }
    }

    /**
     * 修改请假原因
     * @param transactionDTO 修改的内容
     * @return 结果
     */
    @PatchMapping("/updateLeaveRecord")
    public Result updateTransaction(@RequestBody TransactionDTO transactionDTO){
        if (transactionDTO.getId() == null && transactionDTO.getReason() == null){
            return Result.error("请选择要修改的记录并输入要修改的内容");
        } else {
            Map<String,Object> map = ThreadLocalUtil.get();
            String employeeId = (String) map.get("employeeId");
            Integer result = attendanceService.updateTransactionReason(transactionDTO,employeeId);
            if (result == 0){
                return Result.error("已审批请假无法修改");
            } else {
                return Result.success();
            }
        }
    }

    /**
     * 获取所有考勤统计信息
     * @param page 页数
     * @param pageSize 每页大小
     * @param employeeId 员工工号
     * @param yearMonth 年月
     * @param deptId 部门id
     * @param academyId 学院id
     * @param otherDeptId 其他部门id
     * @return 结果
     */
    @GetMapping("/statistics")
    public Result getAllAttendanceStatistics(@RequestParam(defaultValue = "1") Integer page ,
                                             @RequestParam(defaultValue = "10") Integer pageSize,
                                             String employeeId, String yearMonth,Integer deptId, Integer academyId, Integer otherDeptId){
        if ((deptId != null && (academyId != null || otherDeptId != null))
                || (academyId != null && (deptId != null || otherDeptId != null))
                || (otherDeptId != null && (academyId != null || deptId != null))){
            return Result.error("部门、学院、其他部门只能选择一个");
        }
        return Result.success(attendanceService.getAllAttendanceStatistics(page,pageSize,employeeId,yearMonth,deptId,academyId,otherDeptId));

    }
}
